<!-- 设备管理--基础设置-设备类型页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-ledger-wrap">
      <div class="left-contianer">
        <Toggle v-model="expland" className="toggle" />
        <div v-show="expland" class="equip-search-wrap">
          <div class="equip-search-content">
            <px-input v-model="filterText" style="width: 200px; margin-right: 6px" placeholder="请输入关键字搜索" />
            <px-tooltip content="全部收折" placement="top">
              <px-button
                v-show="isTreeOpen"
                style="font-size: 20px"
                link
                type="primary"
                icon="ChevronUpRectangle"
                @click="openOrCloseTree('close')"
              />
            </px-tooltip>
            <px-tooltip content="全部展开" placement="top">
              <px-button
                v-show="!isTreeOpen"
                style="margin-left: 0; font-size: 20px"
                link
                type="primary"
                icon="ChevronDownRectangle"
                @click="openOrCloseTree('open')"
              />
            </px-tooltip>
            <px-tooltip content="清除选中" placement="top">
              <px-button style="margin-left: 4px; font-size: 20px" link type="primary" icon="RefreshLeft" @click="resetCheck" />
            </px-tooltip>
          </div>
          <px-scrollbar class="equip-scroller">
            <px-tree
              ref="treeRef"
              :data="treeData"
              :props="defaultProps"
              :filter-node-method="filterNode"
              node-key="code"
              :default-expanded-keys="['FAC_83abf9', 'FAC_93abf6']"
              :expand-on-click-node="false"
              accordion
              highlight-current
              :expanded-keys="expandedKeys"
              @current-change="nodeChange"
              @node-click="nodeClick"
            />
          </px-scrollbar>
        </div>
      </div>
      <div class="equip-table-wrap">
        <div class="item-status-group">
          <div v-for="(item, index) in statusGroup" :key="index" class="item-group">
            <div class="item" :style="{ backgroundColor: tagBgColorList[item.eqpRunStatus] }" />
            {{ item.eqpRunStatusDesc }}：
            <div class="item" :style="{ color: tagColorList[item.eqpRunStatus] }">{{ item.statusNum }}</div>
          </div>
        </div>
        <div class="equip-title">{{ equipTitle }}</div>
        <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="span">
              <px-form-item label="设备编号/名称">
                <px-input
                  v-model="queryParams.value"
                  style="width: 100%"
                  placeholder="请输入设备编号/名称"
                  maxlength="50"
                  clearable
                  @blur="queryParams.value = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col v-show="!expland" :span="span">
              <EquipClassSelect :noDefault="true" :className="queryParams.className" @changeClassName="changeClassName" @clear="clearClass" />
            </px-col>
            <px-col v-show="!expland" :span="span">
              <EquipSystemTree
                :className="queryParams.className"
                :systemCode="queryParams.systemCode"
                @changeAllSystemCodes="changeAllSystemCodes"
                @changeSystemCodes="changeSystemCodes"
                @clearSystem="clearSystem"
              />
            </px-col>
            <px-col :span="span">
              <EquipCategorySelect
                :className="queryParams.className"
                :systemCodes="systemCodes"
                :categoryId="queryParams.categoryId"
                @changeCategory="changeCategory"
              />
            </px-col>
            <px-col :span="span">
              <EquipTypeSelect
                :className="queryParams.className"
                :systemCodes="systemCodes"
                :categoryId="queryParams.categoryId"
                :typeId="queryParams.typeId"
                @changeType="changeType"
              />
            </px-col>
            <px-col :span="span">
              <px-form-item label="设备运行状态">
                <px-select v-model="queryParams.eqpRunStatus" style="width: 100%" placeholder="请选择设备运行状态" clearable>
                  <px-option v-for="item in eqpRunStatusList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="span">
              <px-form-item label="累计时长">
                <px-date-picker
                  v-model="queryParams.timeRange"
                  type="daterange"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  unlink-panels
                />
              </px-form-item>
            </px-col>
            <px-col class="group-btn" style="flex-grow: 1; max-width: fit-content" :span="span">
              <px-button type="primary" style="margin-right: 8px" @click="queryTable">查询</px-button>
              <px-button style="margin-right: 8px" @click="resetCheck">重置</px-button>
              <px-button v-has="'ALL_EQUIP_RUNMANAGE_STATUS_BATCH_DOWNLOAD'" type="primary" plain style="margin-right: 8px" @click="batchDownload"
                >查询并导出</px-button
              >
              <px-dropdown trigger="click" @command="sortTable">
                <px-button type="primary"
                  >排序
                  <px-icon style="margin-left: 4px"><ArrowDown /></px-icon>
                </px-button>
                <template #dropdown>
                  <px-dropdown-menu>
                    <px-dropdown-item v-for="item in sortArr" :key="item.id" :command="item.value">{{ item.name }}</px-dropdown-item>
                  </px-dropdown-menu>
                </template>
              </px-dropdown>
            </px-col>
          </px-row>
        </px-form>
        <px-table :data="tableData" class="equip-table" size="small" :height="expland ? 'calc(100vh - 366px)' : 'calc(100vh - 410px)'" border>
          <px-table-column label="序号" width="80" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column prop="eqpId" label="设备编号" min-width="120" show-overflow-tooltip />
          <px-table-column prop="eqpName" label="设备名称" min-width="120" show-overflow-tooltip />
          <px-table-column v-if="!expland" prop="classNameDesc" label="科室" min-width="80" show-overflow-tooltip />
          <px-table-column v-if="!expland" prop="systemName" label="系统" min-width="80" show-overflow-tooltip />
          <px-table-column prop="categoryName" label="设备总称" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.categoryName ? scope.row.categoryName : "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="typeName" label="设备类型" min-width="120" show-overflow-tooltip />
          <px-table-column prop="eqpRunStatus" label="设备运行状态" min-width="80" show-overflow-tooltip>
            <template #default="scope">
              <px-tag
                v-if="scope.row.eqpRunStatusValue"
                effect="plain"
                :style="{
                  color: `${scope.row.eqpRunStatus === '5' ? '#000' : '#fff'}`,
                  border: 'none',
                  backgroundColor: `${tagBgColorList[scope.row.eqpRunStatus]}`
                }"
              >
                {{ scope.row.eqpRunStatusValue }}
              </px-tag>
              <span v-else>-</span>
            </template>
          </px-table-column>
          <px-table-column label="状态时长" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.lastTimes === 0 ? 0 : scope.row.lastTimes ? scope.row.lastTimes : "-" }}
            </template>
          </px-table-column>
          <px-table-column prop="runTimes" label="累计运行时长" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.runTimes === 0 ? 0 : scope.row.runTimes ? scope.row.runTimes : "-" }}
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" min-width="80" align="center">
            <template #default="scope">
              <px-tooltip content="详情" placement="top">
                <px-button v-has="'ALL_EQUIP_RUNMANAGE_STATUS_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-table-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 详情页面 -->
    <ViewEquipDetail :isMain="isMain" :rowData="rowData" @backMainPage="backMainPage" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_RUNMANAGE_STATUS"
});
import { queryDictData } from "@/api/common";
import { queryEquipIdLedger, queryEquipLedger, querySystemSelect } from "@/api/equip/archive";
import { queryEquipmentStatusNum } from "@/api/equip/runManage";
import EquipCategorySelect from "@/views/all/equip/components/EquipCategorySelect.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import EquipTypeSelect from "@/views/all/equip/components/EquipTypeSelect.vue";
import dayjs from "dayjs";
import { PxTree } from "px-ui";
import { getCurrentInstance, onMounted, reactive, toRefs, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import Toggle from "./components/Toggle.vue";
import ViewEquipDetail from "./components/ViewEquipDetail.vue";
const tagBgColorList = {
  // 0: "#50a9c7", // 正常
  1: "#10B981", // 运行
  2: "#9254DE", // 故障（报警且停机）/异常停机
  3: "#F59E0B", // 带病（报警且运行）/异常
  4: "#909399", // 离线
  5: "#efefef" // 停机
  // 6: "#ffa299", // 仪表强制
  // 7: "#49b0f5" // 单侧供应
};
const tagColorList = {
  // 0: "#50a9c7", // 正常
  1: "#10B981", // 运行
  2: "#9254DE", // 故障（报警且停机）/异常停机
  3: "#F59E0B", // 带病（报警且运行）/异常
  4: "#909399", // 离线
  5: "#000" // 停机
  // 6: "#ffa299", // 仪表强制
  // 7: "#49b0f5" // 单侧供应
};
const { proxy }: any = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const state = reactive<any>({
  filterText: "",
  treeRef: null,
  treeData: [],
  expandedKeys: [],
  isTreeOpen: true,
  equipTitle: "全部",
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    eqpRunStatus: "",
    isAsc: "desc",
    orderByColumn: "updateTime"
  },
  tableData: [],
  total: 0,
  eqpRunStatusList: [],
  isMain: true, // 主页面true 详情页面false
  rowData: {},
  statusGroup: [],
  systemCodes: [],
  sortArr: [
    { id: "1", value: "1", name: "按更新时间正序" },
    { id: "2", value: "2", name: "按更新时间倒序" },
    { id: "3", value: "3", name: "按编号正序" },
    { id: "4", value: "4", name: "按编号倒序" },
    { id: "5", value: "5", name: "按类型正序" },
    { id: "6", value: "6", name: "按类型倒序" }
  ],
  expland: true
});
const {
  filterText,
  treeRef,
  treeData,
  expandedKeys,
  isTreeOpen,
  equipTitle,
  queryParams,
  tableData,
  total,
  eqpRunStatusList,
  isMain,
  rowData,
  statusGroup,
  systemCodes,
  sortArr,
  expland
} = toRefs(state);
// formItem 宽度
const span = 6;
const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};

// 监视过滤树的值
watch(filterText, val => {
  treeRef.value!.filter(val);
});

const initSpcDate = () => {
  // 获取当前时间
  const now = dayjs();
  // 获取一年前日期
  const oneYearAgo = now.subtract(1, "year").format("YYYY-MM-DD");
  // 获取当前日期
  const nowYear = now.format("YYYY-MM-DD");
  return [oneYearAgo, nowYear]; // 近一年时间范围
};
// 进入页面时触发
onMounted(async () => {
  queryParams.value.timeRange = initSpcDate();
  if (route?.query && route?.query?.id) {
    const params = {
      eqpId: route.query.id
    };
    const data = await queryEquipIdLedger(params);
    rowData.value = data;
    isMain.value = false;
    return;
  }
  if (route?.query && route?.query?.className) {
    queryParams.value.className = route?.query?.className;
  }
  if (route?.query && route?.query?.eqpRunStatus) {
    queryParams.value.eqpRunStatus = route?.query?.eqpRunStatus;
  }
  isMain.value = true;
  queryTree();
  await queryEqpRunStatusSelect();
  if (route?.query && route?.query?.eqpRunStatusName) {
    queryParams.value.eqpRunStatus = eqpRunStatusList.value.find(s => s.name === route?.query?.eqpRunStatusName)?.value;
  }
  queryTable();
});

// 表格排序
const sortTable = command => {
  if (command === "1") {
    queryParams.value.isAsc = "asc";
    queryParams.value.orderByColumn = "updateTime";
  } else if (command === "2") {
    queryParams.value.isAsc = "desc";
    queryParams.value.orderByColumn = "updateTime";
  } else if (command === "3") {
    queryParams.value.isAsc = "asc";
    queryParams.value.orderByColumn = "eqpId";
  } else if (command === "4") {
    queryParams.value.isAsc = "desc";
    queryParams.value.orderByColumn = "eqpId";
  } else if (command === "5") {
    queryParams.value.isAsc = "asc";
    queryParams.value.orderByColumn = "typeId";
  } else if (command === "6") {
    queryParams.value.isAsc = "desc";
    queryParams.value.orderByColumn = "typeId";
  }
  queryTable();
};

// 查询左侧树
const queryTree = async () => {
  const data = await querySystemSelect({});
  treeData.value = data;
};
// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
// 左侧树添加清除选中按钮
const resetCheck = () => {
  filterText.value = "";
  equipTitle.value = "全部";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    isAsc: "desc",
    orderByColumn: "updateTime"
  };
  queryParams.value.timeRange = initSpcDate();
  systemCodes.value = [];
  queryTable();
};
// 点击左侧树节点，获取categoryId，查询设备列表
const nodeClick = () => {
  // 点击右侧切换系统时，清空设备编号名称
  queryParams.value.value = "";
  queryTable();
};
const nodeChange = (e1emData, nodeData) => {
  // 选中e1emData节点
  if (e1emData.type === "factoryArea") {
    // 一级工厂
    equipTitle.value = e1emData.name;
    queryParams.value = {
      ...queryParams.value,
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      systemCodes: []
    };
    queryParams.value.systemCode = "";
    systemCodes.value = [];
    queryParams.value.categoryId = null;
    queryParams.value.typeId = null;
    queryParams.value.modelId = null;
  } else if (e1emData.type === "className") {
    // 二级科室
    equipTitle.value = e1emData.name;
    queryParams.value = {
      ...queryParams.value,
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      className: e1emData.code,
      systemCodes: []
    };
    queryParams.value.systemCode = "";
    systemCodes.value = [];
    queryParams.value.categoryId = null;
    queryParams.value.typeId = null;
    queryParams.value.modelId = null;
  } else if (e1emData.type === "systemCategory") {
    const systemCodeList = [e1emData.code];
    if (e1emData.children && e1emData.children.length > 0) {
      e1emData.children.forEach(item => {
        systemCodeList.push(item.code);
      });
    }
    systemCodes.value = systemCodeList;
    if (nodeData.parent.data.type === "className") {
      // 三级系统
      equipTitle.value = nodeData.parent.data.name + " / " + e1emData.name;
      queryParams.value = {
        ...queryParams.value,
        pageNum: queryParams.value.pageNum,
        pageSize: queryParams.value.pageSize,
        className: nodeData.parent.data.code,
        systemCodes: systemCodeList
      };
    } else {
      if (nodeData.parent?.parent.data.type === "className") {
        // 四级系统
        equipTitle.value = nodeData.parent.parent.data.name + " / " + nodeData.parent.data.name + " / " + e1emData.name;
        queryParams.value = {
          ...queryParams.value,
          pageNum: queryParams.value.pageNum,
          pageSize: queryParams.value.pageSize,
          className: nodeData.parent.parent.data.code,
          systemCodes: systemCodeList
        };
      } else {
        // 五级系统
        equipTitle.value =
          nodeData.parent.parent.parent.data.name +
          " / " +
          nodeData.parent.parent.data.name +
          " / " +
          nodeData.parent.data.name +
          " / " +
          e1emData.name;
        queryParams.value = {
          ...queryParams.value,
          pageNum: queryParams.value.pageNum,
          pageSize: queryParams.value.pageSize,
          className: nodeData.parent.parent.parent.data.code,
          systemCodes: systemCodeList
        };
      }
    }
    queryParams.value.systemCode = e1emData.code;
  }
};
// 获取运行状态数量
const getStatusNum = async () => {
  statusGroup.value = [];
  const params = {
    value: queryParams.value.value,
    className: queryParams.value.className,
    systemCodes: systemCodes.value,
    categoryId: queryParams.value.categoryId,
    typeId: queryParams.value.typeId,
    eqpRunStatus: queryParams.value.eqpRunStatus
  };
  const data = await queryEquipmentStatusNum(params);
  statusGroup.value = data;
};
// 设备运行状态下拉框
const queryEqpRunStatusSelect = async () => {
  const params = {
    typeCode: "EQP_RUN_STATUS"
  };
  const data = await queryDictData(params);
  eqpRunStatusList.value = data || [];
};
// 查询设备列表
const queryTable = async () => {
  const { timeRange = [], ...others } = queryParams.value;
  const data = await queryEquipLedger({
    ...others,
    startTime: timeRange ? timeRange[0] + " 00:00:00" : "",
    endTime: timeRange ? timeRange[1] + " 23:59:59" : "",
    runFlag: true
  });
  tableData.value = data?.data;
  total.value = data?.total;
  getStatusNum();
};
// 运行记录
const handleView = (row: any) => {
  rowData.value = JSON.parse(JSON.stringify(row));
  isMain.value = false;
};
// 状态时长
const statusTimes = time => {
  return Date.parse(new Date()) - Date.parse(new Date(time.replace(/-/g, "/")));
};
// 从详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  queryTable();
  if (route?.query && route?.query?.id) {
    router.push({ query: {} });
  }
};
// 打开或者关闭树
const openOrCloseTree = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};
// 批量下载
const batchDownload = async () => {
  await queryTable();
  const params = {
    value: queryParams.value.value,
    className: queryParams.value.className,
    systemCodes: systemCodes.value,
    categoryId: queryParams.value.categoryId,
    typeId: queryParams.value.typeId,
    eqpRunStatus: queryParams.value.eqpRunStatus,
    startTime: queryParams.value.timeRange ? queryParams.value.timeRange[0] + " 00:00:00" : "",
    endTime: queryParams.value.timeRange ? queryParams.value.timeRange[1] + " 23:59:59" : ""
  };
  proxy.download("post", "/digitaltwins/api/v1/equipment/exportEqpList", params, "设备运行台账.xlsx");
};
// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
  queryParams.value.systemCode = "";
  systemCodes.value = [];
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
  const currentKey = `${val}`;
  treeRef.value!.setCurrentKey(currentKey, true);
  queryTable();
};
const clearClass = () => {
  treeRef.value!.setCurrentKey(`${queryParams.value.className}`);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  queryParams.value.systemCode = val;
  systemCodes.value = val2;
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
  treeRef.value!.setCurrentKey(val, true);
  queryTable();
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  queryParams.value.className = val2;
  queryParams.value.systemCode = val3;
  systemCodes.value = val4;
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
  treeRef.value!.setCurrentKey(val3, true);
  queryTable();
};
// 系统组件值改变触发
const clearSystem = val => {
  queryParams.value.systemCode = "";
  systemCodes.value = [];
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
  const currentKey = `${queryParams.value.className}`;
  treeRef.value!.setCurrentKey(currentKey, true);
  queryTable();
};
// 改变设备总称，清空设备类型
const changeCategory = val => {
  queryParams.value.categoryId = val;
  queryParams.value.typeId = null;
};
// 改变设备类型，清空设备型号
const changeType = (val, val2) => {
  queryParams.value.categoryId = val2;
  queryParams.value.typeId = val;
};
</script>

<style lang="scss" scoped>
.equip-ledger-wrap {
  position: relative;
  box-sizing: border-box;
  display: flex;
  width: 100%;
  height: calc(100vh - 126px);
  padding: 24px 24px 0;
  background-color: #fff;
  border-radius: 8px;

  .left-contianer {
    position: relative;
    margin-right: 16px;
  }

  .equip-search-wrap {
    width: 300px;
    height: calc(100vh - 214px);
    padding: 12px;
    border: 1px solid #dfdfdf;

    .equip-search-content {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
    }

    .equip-scroller {
      height: calc(100vh - 273px);
    }
  }

  .equip-table-wrap {
    flex-grow: 1;
    width: calc(100% - 316px);

    .equip-form {
      .px-form-item {
        width: 100%;
        margin-bottom: 8px;
      }
    }

    .item-status-group {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      height: 28px;

      .item-group {
        display: flex;
        align-items: center;
        margin-left: 20px;

        .item {
          width: 20px;
          height: 20px;
          margin-right: 4px;
        }
      }
    }

    .group-btn {
      :deep(.px-button + .px-button) {
        margin-left: 0;
      }
    }

    .equip-title {
      height: 40px;
      font-weight: bold;
    }

    .equip-table {
      --px-table-border-color: #dfdfdf;

      font-size: 14px;

      :deep(.allSelectDisable .cell) {
        visibility: hidden;
      }
      :deep(.px-table__header) {
        thead {
          tr {
            background-color: #e7eefb !important;

            th {
              font-size: 14px;
              font-weight: bold;
              color: #000;
              background-color: #e7eefb !important;
            }
          }
        }
      }
      :deep(.px-table__cell) {
        padding: 0;
        height: 36px;
        line-height: 36px;
        .cell {
          height: 36px;
          line-height: 36px;
        }
      }
    }

    .equip-table-pagination {
      width: 100%;
      margin: 0;
      height: 64px;
      padding: 16px 0 !important;
      box-sizing: border-box;

      :deep(.px-pagination) {
        right: 0;
      }
    }
  }
}
</style>
